import time

import scipy.io
import numpy as np
import matlab.engine
from scipy import signal

bad_channels = [1, 4, 5, 6, 8, 11, 12, 15, 17]


class RunMat:
    def __init__(self, model_path):
        self.model_path = model_path
        # 加载模型（指定完整路径）
        try:
            self.eng = matlab.engine.start_matlab()
            # 先保存当前工作区变量，避免干扰
            original_vars = set(self.eng.who())
            self.eng.load(model_path, nargout=0)
            # 获取加载后新增的变量（即模型文件中的变量）
            all_vars = set(self.eng.who())
            model_vars = all_vars - original_vars
            if not model_vars:
                raise ValueError(f"模型文件 {model_path} 中未找到任何变量")
            model_name = model_vars.pop()
            print(model_name)
            self.model = self.eng.workspace[model_name]  #
        except matlab.engine.MatlabExecutionError as e:
            print("模型加载失败:", e)

    def run_model(self, data):
        X_test = matlab.double(data.tolist())  # 示例数据
        score1 = self.eng.online_Pred(X_test, self.model)
        return score1

    def close(self):
        self.eng.quit()


if __name__ == '__main__':
    model_path = r"E:\ZHNJ\13-ECOG\猴子\猴脑控光标\20250805\model\trainedModel20250811_fft.mat"

    # ecog_data_dir = r"E:\ZHNJ\13-ECOG\猴子\0806\20250806_115156_上下二向_round1\20250806_115156_上下二向_round1\data_cla_插值\raw_20250806_115156626.npy"
    file_path1 = r"E:\ZHNJ\13-ECOG\猴子\0807\20250807_111958_上下二向_round1\20250807_111958\data_cla_插值\dataset_1.npy"
    loaded_dict = np.load(file_path1, allow_pickle=True).item()
    X1 = loaded_dict['X']
    y1 = loaded_dict['y']
    # X_data = np.load(ecog_data_dir)
    #
    # # %%
    X_test = X1[5000:5010]
    y_test = y1[5000:5010]
    run_mat = RunMat(model_path)
    for i in X_test:
        start_time = time.time()
        score = run_mat.run_model(i.T)
        end_time = time.time()
        print(score)

    run_mat.eng.quit()
